package com.pinjitsu.service;

import com.pinjitsu.entity.Highscore;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import java.util.List;

@Component
public class HighscoreServiceImpl implements HighscoreService {

    EntityManager em;
    Logger logger = Logger.getLogger(HighscoreServiceImpl.class);

    @Override
    @Transactional
    public Highscore saveHighscore(Highscore highscore) {
        em.persist(highscore);
        return highscore;
    }

    @Override
    public Long updateHighscore(Highscore highscore) {
        try {
            // Highscore merged = em.merge(highscore);
            // em.flush();
            // return merged.getFacebookId();
            return null;
        } catch (EntityExistsException e) {
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public List<Highscore> getAllHighscores(int firstResult, int maxResults) {
        return em.createQuery("select o from Highscore o order by o.highscore DESC").setFirstResult(firstResult)
                .setMaxResults(maxResults).getResultList();
    }

    public Long countHighscores() {
        Long count = ((Number) em.createQuery("select count(o) from Highscore o").getSingleResult()).longValue();
        return count;
    }

    public EntityManager getEm() {
        return em;
    }

    @PersistenceContext
    public void setEm(EntityManager em) {
        this.em = em;
    }

    @Override
    public Long getFriendHighscores(Long facebookId, int firstResult, int maxResults) {
        Highscore highscore = null;
        String query = "select o from Highscore o where o.facebookId = :facebookId order by o.highscore DESC";
        try {
            highscore = (Highscore) em.createQuery(query).setParameter("facebookId", facebookId).setMaxResults(1).getSingleResult();
        } catch (NoResultException ex) {
            logger.warn("no result for " + facebookId);
            return null;
        }
        return highscore.getHighscore();
    }

}
